<?php

namespace App\Services;

use App\Models\MaintainModel;

class MaintainService extends BaseService
{

    /**
     * Notes: 获取投诉
     * User: lstink
     * Date: 2021/2/21
     * Time: 11:45 上午
     * @return array
     */
    public function getMaintains($where)
    {
        //获取投诉列表
        $list = MaintainModel::with(['community', 'user'])->where($where)->where(function ($query) {
            //小区
            if (!empty(request()->c_id)) {
                $query->where('c_id', request()->c_id);
            }
            //状态
            if (isset(request()->status)) {
                $query->where('status', request()->status);
            }
            //用户
            if (!empty(request()->user_id)) {
                $query->where('user_id', request()->user_id);
            }
            //时间戳
            if (!empty(request()->created_at) && count(request()->created_at) == 2) {
                $start_time = strtotime(request()->created_at[0]);
                $end_time = strtotime(request()->created_at[1]);
                if ($start_time < $end_time) {
                    $query->where('created_at', '>=', $start_time)->where('created_at', '<=', $end_time);
                } else {
                    $query->where('created_at', '<=', $start_time)->where('created_at', '>=', $end_time);
                }
            }
        })->orderBy('created_at', 'desc')->paginate($param['per_page'] ?? 30);

        return $this->format($list);
    }

    /**
     * Notes: 获取投诉详情内容
     * User: lstink
     * Date: 2021/2/22
     * Time: 9:30 上午
     * @param $id
     * @return array
     */
    public function getMaintainInfoById($id)
    {
        $detail = MaintainModel::with(['community', 'user'])->where(['id' => $id])->first();
        return $this->format($detail);
    }


    /**
     * Notes: 设置状态
     * User: lstink
     * Date: 2021/2/22
     * Time: 9:30 上午
     * @param $id
     * @param int $status
     * @return array
     */
    public function setStatus($id, $data = [])
    {
        $info = MaintainModel::find($id);
        if ($info->status >= 2) {
            return $this->format_error('已经处理完成，不可重复处理');
        }
        if ($info->status == 0) {
            //TODO:必须提交处理人姓名和手机号 备注随意
            $info->username = $data['username'];
            $info->phone = $data['phone'];
            $info->remarks = $data['remarks'] ?? '';
            $info->status = 1;
        } else {
            $info->status = 2;
        }
        return $this->format($info->save());
    }

}
